import { axios } from 'taro-axios'
import Taro from '@tarojs/taro'


const TARO_APP_BASE_URL = "http://47.99.101.116:80"
 
// 公共提示
const shwoErrorToast = (msg) => {
    Taro.showToast({
        title: msg,
        icon: 'none'
    })
}
 
// 请求根路径
const instance = axios.create({
  baseURL: TARO_APP_BASE_URL,
})
 
// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        let token = Taro.getStorageSync('token')
        if (typeof token == undefined || typeof token == 'undefined') {
            token = '';
            if (config.url.indexOf('user') < 0) {
                Taro.navigateTo({
                    url: '/pages/login/login'
                })
            }
        }
        config.headers = {
            'Content-Type': 'application/json;charset=utf-8',
            token:token,
        }
        return config;
    }, (error) => {
        return Promise.reject(error)
    }
)
 
// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        if (response.data.isError) {
            shwoErrorToast(response.data.error.message)
        } else {
            return response.data;
        }
    }, (error) => {
        if (error.response) {
            Taro.hideLoading()
            console.log('err', error)
            
            let res = error.response.data
            switch (res.code) {
                case 400:
                    shwoErrorToast(res.message || '非法请求')
                    break
                case 401:
                    shwoErrorToast('登录过期')// 可以尝试无感登陆或者跳转到登陆页
                    break
                case 403:
                    shwoErrorToast(res.message || '非法请求')
                    break
                case 404:
                    shwoErrorToast(res.message || '非法请求')
                    break
                case 500:
                case 502:
                    shwoErrorToast(res.message || '服务器开小差啦')
                    break
                default:
                    shwoErrorToast(res.message || res.statusText)
            }
        } else {
            console.log(error)
            shwoErrorToast('请检查网络连接状态')
        }
        return Promise.reject(error)
    }
)
 
export default instance